import * as bootstrap from "bootstrap";
import { Ref, getCurrentInstance, onMounted, ref, watch } from "vue";

export function useModal(refValue: Ref<boolean>, key: string) {
  const vm = getCurrentInstance();

  // 1. 定义 modal 与 modalRef
  const modalRef = ref();
  const modal = ref();

  // const { [key]: isShow } = toRefs(props);

  watch(() => refValue.value, () => {
    if (refValue.value){
      show();
    } else {
      hide();
    }
  })

  // 2. 初始化 modal
  onMounted(async() => {
    // 模态框创建
    modal.value = new bootstrap.Modal(modalRef.value, { backdrop: true })

    modalRef.value.addEventListener('hidden.bs.modal', function() {
      vm?.emit(`update:${key}`, false)
    })
  })
  // 3. 定义 showModal 与 hideModal 方法
  function show(){
    modal.value.show();
  }

  function hide(){
    modal.value.hide();
  }

  // 4. 返回一个 status 状态，用于是否显示 modal
  return {
    modal,
    modalRef,
    show,
    hide
  }
}
